<!--  -->
<template>
  <div class="role-manage">
    <div class="query-form">
      <el-form ref="form" :inline="true" :model="queryForm">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="queryForm.menuName" placeholder="请输入菜单名称" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getRoleList">查询</el-button>
          <el-button @click="handleReset('form')">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="base-table">
      <div class="action">
        <el-button type="primary" @click="handleAdd(1)">创建</el-button>
      </div>
      <el-table :data="roleList">
        <!-- <el-table-column width="55" /> -->
        <el-table-column
          v-for="item in columns"
          :key="item.prop"
          :prop="item.prop"
          :label="item.label"
          :width="item.width"
          :formatter="item.formatter"
        />
        <el-table-column label="操作" width="260">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)"
              >编辑</el-button
            >
            <el-button
              size="small"
              type="primary"
              @click="handleOpenPermission(scope.row)"
              >设置权限</el-button
            >
            <el-button
              type="danger"
              size="small"
              @click="handleDel(scope.row._id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="pagination"
        background
        layout="prev, pager, next"
        :total="pager.total"
        :page-size="pager.pageSize"
        @current-change="handleCurrentChange"
      />
    </div>
    <el-dialog title="用户新增" v-model="showModal">
      <el-form
        ref="dialogForm"
        :model="roleForm"
        label-width="100px"
        :rules="rules"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="roleForm.roleName" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            type="textarea"
            :rows="2"
            v-model="roleForm.remark"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer"></span>
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确认</el-button>
      </template>
    </el-dialog>
    <el-dialog title="权限设置" v-model="showPermission">
      <el-form label-width="100px">
        <el-form-item label="角色名称">
          {{ curRoleNmae }}
        </el-form-item>
        <el-form-item label="选择权限">
          <el-tree
            ref="permissionTree"
            :data="menuList"
            show-checkbox
            node-key="_id"
            default-expand-all
            :props="{ label: 'menuName' }"
          >
          </el-tree>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer"></span>
        <el-button @click="showPermission = false">取消</el-button>
        <el-button type="primary" @click="handlePermissionSubmit"
          >确认</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, getCurrentInstance, nextTick } from "vue";
import utils from "../utils/utils";

const { proxy } = getCurrentInstance();

const queryForm = ref({
  roleName: "",
});

const roleList = ref([]);
const pager = ref({
  total: 0,
  pageNum: 1,
  pageSize: 10,
});
const columns = ref([
  {
    label: "角色名称",
    prop: "roleName",
  },
  {
    label: "备注",
    prop: "remark",
  },
  {
    label: "权限列表",
    prop: "permissionList",
    width: 200,
    formatter(row, column, value) {
      let names = [];
      let list = value.halfCheckedKeys || [];
      list.map((key) => {
        let name = actionMap.value[key]
        if (key && name) names.push(name);
      });
      return names.join(",");
    },
  },
  {
    label: "创建时间",
    prop: "createTime",
    width: 160,
    formatter(row, column, value) {
      return utils.formateDate(new Date(value));
    },
  },
  {
    label: "更新时间",
    prop: "updateTime",
    width: 160,
    formatter(row, column, value) {
      return utils.formateDate(new Date(value));
    },
  },
]);

const roleForm = ref({});

const showModal = ref(false);
const action = ref("create");

const rules = ref({
  roleName: [{ required: true, message: "请输入角色名称", trigger: "blur" }],
});

const showPermission = ref(false);

const curRoleNmae = ref("");
const curRoleId = ref("");

const menuList = ref([]);

const actionMap = ref({});

const getRoleList = async () => {
  try {
    let { list, page } = await proxy.$api.getRoleList({
      ...queryForm.value,
      ...pager.value,
    });
    roleList.value = list;
    pager.value.total = page.total;
  } catch (error) {
    throw new Error(error);
  }
};
getRoleList();

const getMenuList = async () => {
  try {
    let list = await proxy.$api.getMenuList();
    // console.log('list', list);
    menuList.value = list;
    getActionMap(list);
  } catch (error) {
    throw new Error(error);
  }
};
getMenuList();

const handleReset = (form) => {
  proxy.$refs[form].resetFields();
};

const handleAdd = (type, row) => {
  showModal.value = true;
  action.value = "create";
};

const handleEdit = async (row) => {
  action.value = "edit";
  showModal.value = true;
  await nextTick(() => {
    roleForm.value = JSON.parse(JSON.stringify({
      _id: row._id,
      roleName: row.roleName,
      remark: row.remark
    }));
  });
};

const handleDel = async (_id) => {
  await proxy.$api.roleOperate({ _id, action: "delete" });
  proxy.$message.success("删除成功");
  getRoleList();
};

const handleClose = () => {
  handleReset("dialogForm");
  showModal.value = false;
};

const handleSubmit = () => {
  proxy.$refs.dialogForm.validate(async (valid) => {
    if (valid) {
      // let roleForms = roleForm.value
      let params = { ...roleForm.value };
      params.action = action.value;
      let res = await proxy.$api.roleOperate(params);
      if (res) {
        showModal.value = false;
        proxy.$message.success("创建成功");
        handleReset("dialogForm");
        getRoleList();
      }
    }
  });
};

const handleCurrentChange = (current) => {
  pager.value.pageNum = current
  getRoleList()
};

const handleOpenPermission = (row) => {
  curRoleId.value = row._id;
  curRoleNmae.value = row.roleName;
  showPermission.value = true;
  let { checkedKeys } = row.permissionList;
  setTimeout(() => {
    proxy.$refs.permissionTree.setCheckedKeys(checkedKeys);
  });
};

const handlePermissionSubmit = async () => {
  let nodes = proxy.$refs.permissionTree.getCheckedNodes();
  let halfKeys = proxy.$refs.permissionTree.getHalfCheckedKeys();
  let checkedKeys = [];
  let parentKeys = [];
  nodes.map((node) => {
    if (!node.children) {
      checkedKeys.push(node._id);
    } else {
      parentKeys.push(node._id);
    }
  });
  let params = {
    _id: curRoleId.value,
    permissionList: {
      checkedKeys,
      halfCheckedKeys: parentKeys.concat(halfKeys),
    },
  };
  await proxy.$api.updatePermission(params);
  showPermission.value = false;
  proxy.$message.success("设置成功");
  getRoleList();
};

const getActionMap = (list) => {
  let actionmap = {};
  const deep = (arr) => {
    while (arr.length) {
      let item = arr.pop();
      if (item.children && item.action) {
        actionmap[item._id] = item.menuName;
      }
      if (item.children && !item.action) {
        deep(item.children);
      }
    }
  };
  deep(JSON.parse(JSON.stringify(list)));
  actionMap.value = actionmap;
};
</script>
<style lang="scss"></style>
